<?php

namespace common\core\behaviors;

use common\helpers\BaseHelper;
use common\helpers\CodeHelper;
use yii\base\Behavior;
use yii\base\Controller;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;

class Permission extends Behavior
{

    /**
     * is open validate
     * @var bool
     */
    public $isValidate;

    /**
     *  supper admin account
     *
     * @var string
     */
    public $admin;

    /**
     * translate action name
     *
     * @var array
     */
    public $actionNames;

    /**
     * is record action permission
     *
     * @var bool
     */
    private $isRecord;

    /**
     * permission name
     *
     * @var string
     */
    private $permission;

    public function events()
    {
        $events = parent::events();
        $events = ArrayHelper::merge($events, [
            Controller::EVENT_AFTER_ACTION => 'addPermission',
            Controller::EVENT_BEFORE_ACTION => 'validatePermission',
        ]);
        return $events;
    }

    public function init()
    {
        parent::init();

        if ($this->isValidate === null) {
            $this->isValidate = false;
        }

        if ($this->admin === null) {
            $this->admin = ArrayHelper::getValue(\Yii::$app->params, 'supperAdmin', '-1');
        }

        if ($this->actionNames === null) {
            $this->actionNames = [
                'add' => '添加',
                'edit' => '编辑',
                'delete' => '删除',
                'update' => '更新',
            ];
        }

        $this->isRecord = ArrayHelper::getValue(\Yii::$app->params, 'initPermission', YII_ENV_DEV);
        $this->permission = DIRECTORY_SEPARATOR . \Yii::$app->controller->uniqueId . DIRECTORY_SEPARATOR . \Yii::$app->controller->action->id;
    }

    /**
     * add permission
     *
     * @param $event
     *
     * @return mixed
     * @throws \Exception
     */
    public function addPermission($event)
    {
        $actionId = \Yii::$app->controller->action->id;
        $auth = \Yii::$app->authManager;
        $hasPermission = $auth->getPermission($this->permission);
        if ($this->isRecord && $hasPermission === null) {
            if (!empty($event->sender->view->params['breadcrumbs'])) {
                $breadcrumbs = [];
                foreach ($event->sender->view->params['breadcrumbs'] as $breadcrumb) {
                    $breadcrumbs[] = is_array($breadcrumb) ? $breadcrumb['label'] : $breadcrumb;
                }
                if (!empty($this->actionNames[$actionId])) {
                    array_pop($breadcrumbs);
                    $breadcrumbs[] = $this->actionNames[$actionId];
                }
                $description = implode('-', $breadcrumbs);
            } else {
                $description = $this->permission;
            }
            $add = $auth->createPermission($this->permission);
            //$add->description = $description;
            $auth->add($add);
        }
        return $event;
    }

    /**
     * validate permission
     *
     * @throws \yii\base\UserException
     */
    public function validatePermission()
    {
        $identity = \Yii::$app->user->identity;
        $visible = (isset($identity['username']) ? $identity['username'] : '') === $this->admin ? false : true;
        if ($this->isValidate && $visible && !\Yii::$app->user->can($this->permission)) {
            //BaseHelper::invalidException(CodeHelper::SYS_REQUEST_ERROR, CodeHelper::getCodeText(CodeHelper::SYS_REQUEST_ERROR));
            throw new ForbiddenHttpException('没有权限访问');

        }
    }

}
